package main

import (
	"log"
	"runtime"
	"time"
)

var lastTotalFreed uint64
var intMap map[int]int
var cnt = 8192

func printMemStats() {
	log.Println("###################")
	var m runtime.MemStats
	runtime.ReadMemStats(&m)
	log.Printf("Alloc = %v TotalAlloc=%v Just Freed = %v Sys = %v NumGc=%v\n",
		m.Alloc/1024, m.TotalAlloc/1024, ((m.TotalAlloc-m.Alloc)-lastTotalFreed)/1024, m.Sys/1024, m.NumGC)
	lastTotalFreed = m.TotalAlloc - m.Alloc
}

func initMap() {
	intMap = make(map[int]int, cnt)

	for i := 0; i < cnt; i++ {
		intMap[i] = i
	}
}

func main() {
	// 打印内存分配信息
	printMemStats()

	// 1.分配内存后，手动执行GC
	initMap()
	runtime.GC()
	// 1.打印内存分配信息
	printMemStats()

	// 2.删除数据，手动执行GC
	log.Println(len(intMap))
	for i := 0; i < cnt; i++ {
		delete(intMap, i)
	}
	log.Println(len(intMap))
	runtime.GC()
	// 2.打印内存分配信息
	printMemStats()

	// 3.置空对象，等待2分钟自动gc
	intMap = nil
	for {
		time.Sleep(1 * time.Minute)
		printMemStats()
	}
}
